package com.java.code.rocketmq.filter;

import com.java.code.rocketmq.RocketmqConstants;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 如果这个消费者过滤了消息,那么剩下的消息自动过掉了.不会产生堆积
 * @author weichuanyuan
 * @e-mail wei.cy@bsoft.com.cn
 * @date 2022/09/01 19:14
 * @package com.java.code.rocketmq.filter
 * @description
 */
public class FilterConsume {
    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(RocketmqConstants.GROUP);
        // 指定Namesrv地址信息.
        consumer.setNamesrvAddr(RocketmqConstants.NAMESVR_ADDR);
        //负载均衡模式消费 taga 和 tagb也会进入消费
        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 只有订阅的消息有这个属性a, a >=0 and a <= 3
        consumer.subscribe(RocketmqConstants.TOPIC, MessageSelector.bySql("a between 0 and 3"));
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt message : msgs) {
                    // Print approximate delay time period
                    System.out.println("Receive message[msgId=" + message.getMsgId() + "] "
                            + "message=[" + new String(message.getBody()) +"]"
                            + (System.currentTimeMillis() - message.getBornTimestamp()) + "ms later");
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
    }
}
